package fr.jade.fraclite.control.attribute;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.objectweb.fractal.api.factory.InstantiationException;

import fr.jade.fraclite.InitializationContext;
import fr.jade.fraclite.api.Controller;
import fr.jade.fraclite.api.control.GenericAttributeController;
import fr.jade.fraclite.api.control.NoSuchAttributeException;

public class BasicGenericAttributeController implements Controller, GenericAttributeController {

    /**
     * The attributes.
     */
    Map<String, String> atts = null;
    GenericAttributeController innerImpl = null;
  
    public void initFcController(InitializationContext ic) throws InstantiationException {
      if(ic.content instanceof GenericAttributeController){
        innerImpl = (GenericAttributeController)ic.content;
      }else{
        atts = new HashMap<String, String>();
      }
    }
    
    /**
     * retrieve an attribute identified by its name.
     * 
     * @param name
     *            the name of the attribute to read.
     * @return the String value of the attribute identified by its name. null if
     *         the implementation does not implements
     *         GenericAttributeController.
     * @throws NoSuchAttributeException
     *             if the given attribute is unknow.
     */
    public String getAttribute(String name) throws NoSuchAttributeException {
      if(innerImpl != null){
        return innerImpl.getAttribute(name);
      } else {
        String value = (String) (atts.get(name));
        if(value == null){
          throw new NoSuchAttributeException(name);
        }else{
          return value;
        }
      }
    }

    /**
     * set the value of an attribute identified by its name and and then
     * notifies the dual level of the attribute setting.
     * 
     * @param name
     *            the name of the attribute to set.
     * @param value
     *            the value of the attribute.
     * @throws NoSuchAttributeException
     *             if the given attribute is unknow.
     */
    public void setAttribute(String name, String value) throws NoSuchAttributeException {
      if(innerImpl != null){
        innerImpl.setAttribute(name, value);
      } else {
        atts.put(name, value);
      }
    }


    public String[] listFcAtt() {
      if(innerImpl != null){
        return innerImpl.listFcAtt();
      } else {
        Set<String> keys = atts.keySet();
        return (String[]) (keys.toArray(new String[keys.size()]));
      }
    }

}
